package org.tinygame.herostory.cmdHandler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.tinygame.herostory.Broadcaster;
import org.tinygame.herostory.model.MoveState;
import org.tinygame.herostory.model.User;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

/**
 * @author shkstart
 * @create 2022-05-05 10:21
 */
public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd>{

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserMoveToCmd cmd) {
        if(null==ctx||null==cmd){
            return;
        }
        //将通道上附着的用户id取出
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if(null==userId){
            return;
        }

        //获取信道用户
        User moveUser= UserManager.getUserById(userId);
        if(null==moveUser){
            return;
        }
        //获取信道用户移动状态属性
        MoveState mvState= moveUser.moveState;

        //从cmd中获取位置和时间，赋值到该用户的移动状态属性中
        mvState.fromPosX=cmd.getMoveFromPosX();
        mvState.fromPosY=cmd.getMoveFromPosY();
        mvState.toPosX=cmd.getMoveToPosX();
        mvState.toPosY=cmd.getMoveToPosY();
        mvState.startTime=System.currentTimeMillis();


        GameMsgProtocol.UserMoveToResult.Builder resultBuilder=GameMsgProtocol.UserMoveToResult.newBuilder();
        resultBuilder.setMoveUserId(userId);
        resultBuilder.setMoveToPosX(mvState.toPosX);
        resultBuilder.setMoveToPosY(mvState.toPosY);
        resultBuilder.setMoveFromPosX(mvState.fromPosX);
        resultBuilder.setMoveFromPosY(mvState.fromPosY);
        resultBuilder.setMoveStartTime(mvState.startTime);

        //构建结果并发送
        GameMsgProtocol.UserMoveToResult newResult=resultBuilder.build();
        Broadcaster.broadcast(newResult);
    }
}
